package com.credithc.customers.manager.service.impl;

import com.credithc.baseserv.core.service.impl.BaseServiceImpl;
import com.credithc.baseserv.core.utils.DateTimeUtils;
import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.factory.DictionaryFactory;
import com.credithc.customers.base.mapper.*;
import com.credithc.customers.base.po.*;
import com.credithc.customers.base.service.ICacheService;
import com.credithc.customers.base.service.ICommonService;
import com.credithc.customers.base.utils.ClassUtils;
import com.credithc.customers.base.utils.CustomerUtils;
import com.credithc.customers.base.utils.IdCardUtils;
import com.credithc.customers.manager.mapper.CustomerExtendStatisticMapper;
import com.credithc.customers.manager.mapper.CustomerManagerMapper;
import com.credithc.customers.manager.po.CustomerExtendStatisticPo;
import com.credithc.customers.manager.ro.CompanyCustomerInfoRo;
import com.credithc.customers.manager.ro.CustomerInfoRo;
import com.credithc.customers.manager.ro.PreCustomerInfoRo;
import com.credithc.customers.manager.service.DesensitizationService;
import com.credithc.customers.manager.service.ICustomerInfoService;
import com.credithc.customers.manager.utils.StatsUtils;
import com.credithc.customers.manager.vo.CompanyCustomerInfoVo;
import com.credithc.customers.manager.vo.CustomerInfoVo;
import com.credithc.customers.manager.vo.PreCustomerExtendVo;
import com.credithc.customers.manager.vo.PreCustomerInfoVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title:
 * @Author: Denghx
 * @Date: 2018/12/17 1:48
 * @Description: com.credithc.customers.manager.service.impl
 * @Version: V1.0.0
 */
@Service
@Slf4j
public class CustomerInfoServiceImpl extends BaseServiceImpl<PreCustomerInfoPo, PreCustomerInfoRo, PreCustomerInfoVo> implements ICustomerInfoService {
    @Autowired
    private CustomerIdInfoMapper customerIdInfoMapper;
    @Autowired
    private CompanyIdInfoMapper companyIdInfoMapper;
    @Autowired
    private CustomerManagerMapper customerManagerMapper;
    @Autowired
    private CustomerExtendMapper customerExtendMapper;
    @Autowired
    private CustomerRelationInfoMapper relationMapper;
    @Autowired
    private CustomerContactInfoMapper contactMapper;
    @Autowired
    private CustomerContactFlowMapper contactFlowMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerMergeFlowMapper customerMergeFlowMapper;
    @Autowired
    private CustomerAccountMapper accountMapper;
    @Autowired
    private CustomerRoleMapper customerRoleMapper;
    @Autowired
    private BizModifyMapper bizMapper;
    @Autowired
    private CustomerProductMapper customerProductMapper;
    @Autowired
    private CustomerStatsMapper statsMapper;
    @Autowired
    private DesensitizationService desensitizationService;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private CustomerManageStatisticMapper manageStatisticMapper;
    @Autowired
    private CustomerExtendStatisticMapper customerExtendStatisticMapper;
    @Autowired
    private CustomerManageInfoMapper customerManageInfoMapper;

    @Override
    public PageInfo<PreCustomerInfoVo> selectAllPre(PreCustomerInfoRo ro) {
        try {
            Example example = new Example(PreCustomerInfoPo.class);
            Example.Criteria criteria = example.createCriteria();
            example.setOrderByClause("create_time desc");
//            if (StringUtils.isNotEmpty(ro.getContactType())) {
//                criteria.andEqualTo("contactType", ro.getContactType());
//            }
            if (StringUtils.isNotEmpty(ro.getContactInfo())) {
                criteria.andEqualTo("contactType", CustomerConstants.CONTACT_TYPE_MOBILE);
                criteria.andEqualTo("contactInfo", ro.getContactInfo());
            }
            if (StringUtils.isNotEmpty(ro.getPreCustomerNo())) {
                criteria.andEqualTo("preCustomerNo", ro.getPreCustomerNo());
            }
            if (StringUtils.isNotBlank(ro.getCreateTimeStart()) && StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andBetween("createTime", ro.getCreateTimeStart(), ro.getCreateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("createTime", ro.getCreateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andLessThanOrEqualTo("createTime", ro.getCreateTimeEnd());
            }
            if (StringUtils.isNotBlank(ro.getUpdateTimeStart()) && StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andBetween("updateTime", ro.getUpdateTimeStart(), ro.getUpdateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("updateTime", ro.getUpdateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andLessThanOrEqualTo("updateTime", ro.getUpdateTimeEnd());
            }
            PageInfo<PreCustomerInfoPo> pageInfo = this.queryPageResultByExample(example, ro.getPageNo(), ro.getPageSize());
            desensitizationService.desensitizationList(pageInfo.getList());
            List<PreCustomerInfoVo> vos = new ArrayList<>();
            if (pageInfo.getTotalCount() > 0) {
                for (PreCustomerInfoPo po : pageInfo.getList()) {
                    PreCustomerInfoVo vo = new PreCustomerInfoVo();
                    BeanUtils.copyProperties(po, vo);
                    if (po.getCreateTime() != null) {
                        vo.setCreateTime(DateTimeUtils.dateToStrLong(po.getCreateTime()));
                    }
                    if (po.getUpdateTime() != null) {
                        vo.setUpdateTime(DateTimeUtils.dateToStrLong(po.getUpdateTime()));
                    }
                    //发送方式
                    Map<String, String> contactTypeMap = DictionaryFactory.Dict.CONTACT_TYPE.getDictMap();
                    if (StringUtils.isNotEmpty(po.getContactType())) {
                        vo.setContactType(contactTypeMap.get(po.getContactType()));
                    }
                    vos.add(vo);
                }
            }
            return new PageInfo<>(vos, pageInfo.getTotalCount(), ro.getPageNo(), ro.getPageSize());
        } catch (DataAccessException e) {
            log.info("查询用户信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public PageInfo<CustomerInfoVo> selectAllCustomer(CustomerInfoRo ro) {
        try {
            int count;
            /*Example example = new Example(CustomerIdInfoPo.class);
            Example.Criteria criteria = example.createCriteria();
            example.setOrderByClause("create_time desc");
            if (StringUtils.isNotEmpty(ro.getCustomerNo())) {
                criteria.andEqualTo("customerNo", ro.getCustomerNo());
            }
            if (StringUtils.isNotEmpty(ro.getCustomerName())) {
                criteria.andEqualTo("customerName", ro.getCustomerName());
            }
            if (StringUtils.isNotEmpty(ro.getCustomerType())) {
                criteria.andEqualTo("customerType", ro.getCustomerType());
            }
            if (StringUtils.isNotEmpty(ro.getIdCardType())) {
                criteria.andEqualTo("idCardType", ro.getIdCardType());
            }
            if (StringUtils.isNotEmpty(ro.getIdCardNo())) {
                criteria.andEqualTo("idCardNo", ro.getIdCardNo());
            }
            if (StringUtils.isNotBlank(ro.getCreateTimeStart()) && StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andBetween("createTime", ro.getCreateTimeStart(), ro.getCreateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("createTime", ro.getCreateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andLessThanOrEqualTo("createTime", ro.getCreateTimeEnd());
            }
            if (StringUtils.isNotBlank(ro.getUpdateTimeStart()) && StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andBetween("updateTime", ro.getUpdateTimeStart(), ro.getUpdateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("updateTime", ro.getUpdateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andLessThanOrEqualTo("updateTime", ro.getUpdateTimeEnd());
            }
            criteria.andEqualTo("customerProperty", 1);
            if (StringUtils.isNotBlank(ro.getSystemSign())) {
                criteria.andLike("subSystemSign", "%" + ro.getSystemSign() + "%");
            }*/
            //如果查询条件只包括系统标识和时间走以下查询
            if (StringUtils.isBlank(ro.getCustomerNo()) && StringUtils.isBlank(ro.getCustomerName()) && StringUtils.isBlank(ro.getCustomerType()) && StringUtils.isBlank(ro.getIdCardType()) && StringUtils.isBlank(ro.getIdCardNo())) {
                String createTimeEnd = ro.getCreateTimeEnd();
                String createTimeStart = ro.getCreateTimeStart();
                if (StringUtils.isBlank(ro.getCreateTimeEnd())) {
                    createTimeEnd = StatsUtils.getCurrentTime().substring(0, 10);
                }
                String subSystemSign = ro.getSystemSign();
                int countEndDay;
                String countStartSum = "0";
                String nextDate = StatsUtils.getPostDate(1, createTimeEnd);
                String endDate = StatsUtils.getPastDate(1, createTimeEnd.substring(0, 10));
                if (StringUtils.isBlank(ro.getSystemSign())) {
                    subSystemSign = "ALL";
                    if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                        countEndDay = 0;
                    } else {
                        countEndDay = manageStatisticMapper.getTodaySumByAll(subSystemSign, nextDate, createTimeEnd);
                    }
                    if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                        String startDate = StatsUtils.getPastDate(1, createTimeStart.substring(0, 10));
                        countStartSum = manageStatisticMapper.getPastSum(subSystemSign, startDate);
//                        countStartDay = manageStatisticMapper.getTodaySumByAll(subSystemSign, createTimeStart, createTimeStart.substring(0, 10));
                    }
                } else {
                    if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                        countEndDay = 0;
                    } else {
                        countEndDay = manageStatisticMapper.getTodaySumBySys(subSystemSign, createTimeEnd);
                    }
                    if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                        String startDate = StatsUtils.getPastDate(1, createTimeStart.substring(0, 10));
                        countStartSum = manageStatisticMapper.getPastSum(subSystemSign, startDate);
//                        countStartDay = manageStatisticMapper.getTodaySumBySys(subSystemSign, createTimeStart.substring(0, 10));
                    }
                }
                String countEndSum = manageStatisticMapper.getPastSum(subSystemSign, endDate);
                if (countEndSum == null) {
                    countEndSum = "0";
                }
                if (countStartSum == null) {
                    countStartSum = "0";
                }
                count = Integer.parseInt(countEndSum) + countEndDay - Integer.parseInt(countStartSum);
            } else {
                count = customerManagerMapper.getListCount(ro);
            }
//            count = customerIdInfoMapper.selectCountByExample(example);
            List<CustomerInfoVo> vos = new ArrayList<>();
            if (count > 0) {
                List<CustomerIdInfoPo> pos;
                //if (StringUtils.isBlank(ro.getCustomerNo()) && StringUtils.isBlank(ro.getCustomerName()) && StringUtils.isBlank(ro.getCustomerType()) && StringUtils.isBlank(ro.getIdCardType()) && StringUtils.isBlank(ro.getIdCardNo()) && StringUtils.isNotBlank(ro.getSystemSign())) {
                Integer startPage = ro.getPageSize() * (ro.getPageNo() - 1);
                ro.setStartPage(startPage);
                pos = customerManagerMapper.getList(ro);
                /*} else {
                    RowBounds rowBounds = new RowBounds(ro.getPageSize() * (ro.getPageNo() - 1), ro.getPageSize());
                    pos = customerIdInfoMapper.selectByExampleAndRowBounds(example, rowBounds);
                }*/
                for (CustomerIdInfoPo po : pos) {
                    CustomerInfoVo vo = new CustomerInfoVo();
                    BeanUtils.copyProperties(po, vo);
                    if (po.getCreateTime() != null) {
                        vo.setCreateTime(DateTimeUtils.dateToStrLong(po.getCreateTime()));
                    }
                    if (po.getUpdateTime() != null) {
                        vo.setUpdateTime(DateTimeUtils.dateToStrLong(po.getUpdateTime()));
                    }
                    if (po.getElementsTime() != null) {
                        vo.setElementsTime(DateTimeUtils.dateToStrLong(po.getElementsTime()));
                    }
                    //证件类型
                    Map<String, String> idTypeMap = DictionaryFactory.Dict.ID_TYPE.getDictMap();
                    if (StringUtils.isNotEmpty(po.getIdCardType())) {
                        vo.setIdCardType(idTypeMap.get(po.getIdCardType()));
                    }
                    //是否三要素验证
                    Map<String, String> elementsMap = DictionaryFactory.Dict.ELEMENTS_STATUS.getDictMap();
                    if (StringUtils.isNotEmpty(po.getElementsVerified())) {
                        vo.setElementsVerified(elementsMap.get(po.getElementsVerified()));
                    }
                    if (po.getIdCardType() != null && po.getIdCardType().equals(CustomerConstants.CERTIFICATE_TYPE_ID_CARD)) {
                        Map<String, String> map = IdCardUtils.getBirAgeSex(po.getIdCardNo());
                        vo.setSex(map.get("sexCode"));
                        vo.setBirth(map.get("birthday"));
                    }
                    List<String> systemList = Arrays.asList(po.getSubSystemSign().split(","));
                    String subSystemSign = "";
                    for (String system : systemList) {
                        subSystemSign += cacheService.getSystemNameBySign(system) + "  ";
                    }
                    vo.setSystemName(subSystemSign);
                    vos.add(vo);
                    desensitizationService.desensitizationList(vos);
                }
            }
            return new PageInfo<>(vos, count, ro.getPageNo(), ro.getPageSize());
        } catch (DataAccessException e) {
            log.error("查询个人客户信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public PageInfo<CompanyCustomerInfoVo> selectAllCompany(CompanyCustomerInfoRo ro) {
        try {
            Example example = new Example(CompanyIdInfoPo.class);
            Example.Criteria criteria = example.createCriteria();
            example.setOrderByClause("create_time desc");
            if (StringUtils.isNotEmpty(ro.getCustomerNo())) {
                criteria.andEqualTo("customerNo", ro.getCustomerNo());
            }
            if (StringUtils.isNotEmpty(ro.getCustomerName())) {
                criteria.andEqualTo("customerName", ro.getCustomerName());
            }
            if (StringUtils.isNotEmpty(ro.getCustomerType())) {
                criteria.andLike("customerNo", ro.getCustomerType() + "%");
            }
            if (StringUtils.isNotEmpty(ro.getIdCardType())) {
                criteria.andEqualTo("idCardType", ro.getIdCardType());
            }
            if (StringUtils.isNotEmpty(ro.getOrgNo())) {
                criteria.andEqualTo("orgNo", ro.getOrgNo());
            }
            if (StringUtils.isNotEmpty(ro.getUnifiedCode())) {
                criteria.andEqualTo("unifiedCode", ro.getUnifiedCode());
            }
            if (StringUtils.isNotBlank(ro.getCreateTimeStart()) && StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andBetween("createTime", ro.getCreateTimeStart(), ro.getCreateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("createTime", ro.getCreateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andLessThanOrEqualTo("createTime", ro.getCreateTimeEnd());
            }
            if (StringUtils.isNotBlank(ro.getUpdateTimeStart()) && StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andBetween("updateTime", ro.getUpdateTimeStart(), ro.getUpdateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("updateTime", ro.getUpdateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andLessThanOrEqualTo("updateTime", ro.getUpdateTimeEnd());
            }
            if (StringUtils.isNotBlank(ro.getSystemSign())) {
                criteria.andLike("subSystemSign", "%" + ro.getSystemSign() + "%");
            }
            List<CompanyCustomerInfoVo> vos = new ArrayList<>();
            int count = companyIdInfoMapper.selectCountByExample(example);
            if (count > 0) {
                RowBounds rowBounds = new RowBounds(ro.getPageSize() * (ro.getPageNo() - 1), ro.getPageSize());
                List<CompanyIdInfoPo> pos = companyIdInfoMapper.selectByExampleAndRowBounds(example, rowBounds);
                desensitizationService.desensitizationList(pos);
                for (CompanyIdInfoPo po : pos) {
                    CompanyCustomerInfoVo vo = new CompanyCustomerInfoVo();
                    BeanUtils.copyProperties(po, vo);
                    if (po.getCreateTime() != null) {
                        vo.setCreateTime(DateTimeUtils.dateToStrLong(po.getCreateTime()));
                    }
                    if (po.getUpdateTime() != null) {
                        vo.setUpdateTime(DateTimeUtils.dateToStrLong(po.getUpdateTime()));
                    }
                    if (po.getElementsTime() != null) {
                        vo.setElementsTime(DateTimeUtils.dateToStrLong(po.getElementsTime()));
                    }
                    //是否三要素验证
                    Map<String, String> elementsMap = DictionaryFactory.Dict.ELEMENTS_STATUS.getDictMap();
                    if (StringUtils.isNotEmpty(po.getElementsVerified())) {
                        vo.setElementsVerified(elementsMap.get(po.getElementsVerified()));
                    }
                    //证件类型
                    Map<String, String> idTypeMap = DictionaryFactory.Dict.ID_TYPE.getDictMap();
                    if (StringUtils.isNotEmpty(po.getIdCardType())) {
                        vo.setIdCardType(idTypeMap.get(po.getIdCardType()));
                    }
                    String prefix = po.getCustomerNo().substring(0, 1);
                    if (CustomerConstants.CUSTOMER_TYPE_FINANCE.equals(prefix) || CustomerConstants.CUSTOMER_TYPE_COMPANY.equals(prefix)) {
                        vo.setCustomerType(DictionaryFactory.Dict.CUSTOMER_TYPE.getDictMap().get(prefix));
                    }
                    List<String> systemList = Arrays.asList(po.getSubSystemSign().split(","));
                    String subSystemSign = "";
                    for (String system : systemList) {
                        subSystemSign += cacheService.getSystemNameBySign(system) + "  ";
                    }
                    vo.setSystemName(subSystemSign);

                    vos.add(vo);
                }
            }
            return new PageInfo<>(vos, count, ro.getPageNo(), ro.getPageSize());
        } catch (DataAccessException e) {
            log.info("查询对公客户信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> selectPreExtend(String preCustomerNo) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            //客户转化来源
            List<Map<String, Object>> preChanges = getPreChange(preCustomerNo);
            map.put("preChanges", preChanges);
            List<Map<String, Object>> preExtends = new ArrayList<>();
            List<PreCustomerExtendVo> vos = customerManagerMapper.selectPreExtend(preCustomerNo);
            desensitizationService.desensitizationList(vos);
            for (PreCustomerExtendVo vo : vos) {
                //拓展信息
                String result = "";
                if (StringUtils.isNotBlank(vo.getCustomerName())) {
                    result = result + " 客户姓名：" + vo.getCustomerName() + "；  ";
                }
                if (StringUtils.isNotBlank(vo.getIdCardType())) {
                    result = result + " 证件类型：" + DictionaryFactory.Dict.ID_TYPE.getDictMap().get(vo.getIdCardType()) + "； ";
                }
                if (StringUtils.isNotBlank(vo.getIdCardNo())) {
                    result = result + " 证件号码：" + vo.getIdCardNo() + "；  ";
                }
                if (StringUtils.isNotBlank(vo.getRemark())) {
                    result = result + " 备注：" + vo.getRemark() + "；  ";
                }
                //todo 用户开户需要调整此字段对应位置cust_extend关联与客户信息
//                if (StringUtils.isNotBlank(vo.getAssociatePreNo())) {
//                    result = result + " 关联用户号：" + vo.getAssociatePreNo() + ";  ";
//                }
                Map<String, Object> preExtend = new HashMap<>();
                preExtend.put("systemSign", cacheService.getSystemNameBySign(vo.getSystemSign()));
                preExtend.put("subSystemSign", cacheService.getSystemNameBySign(vo.getSubSystemSign()));
                preExtend.put("createTime", vo.getCreateTime());
                preExtend.put("remark", result);
                preExtends.add(preExtend);
            }
            map.put("preChanges", preChanges);
            map.put("preExtends", preExtends);
            return map;
        } catch (DataAccessException e) {
            log.info("查询用户拓展信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> selectPreChange(String preCustomerNo) {
        try {
            Map<String, Object> map = new HashMap<>(1);
            Example example = new Example(CustomerExtendPo.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isNotEmpty(preCustomerNo)) {
                criteria.andEqualTo("preCustomerNo", preCustomerNo);
            }
            int total = customerExtendMapper.selectCountByExample(example);
            criteria.andIsNotNull("customerNo");
            int changed = customerExtendMapper.selectCountByExample(example);
            map.put("total", total);
            map.put("changed", changed);
            return map;
        } catch (DataAccessException e) {
            log.info("查询用户转化信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> selectPreStatic() {
        try {
            Map<String, Object> map = new HashMap<>(1);
            int total = 0;
            int changed = 0;
            Example example = new Example(CustomerStatsPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("statsType", CustomerConstants.STATS_PRE_CUSTOMER_CHANGE);
            List<CustomerStatsPo> statsPos = statsMapper.selectByExample(example);
            for (CustomerStatsPo po : statsPos) {
                if ("preTotal".equals(po.getType())) {
                    total = po.getCount();
                } else if ("preChange".equals(po.getType())) {
                    changed = po.getCount();
                }
            }

            map.put("total", total);
            map.put("changed", changed);
            return map;
        } catch (DataAccessException e) {
            log.info("查询用户转化率报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> selectCustomerExtend(String customerNo) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            //证件信息
            List<Map<String, Object>> idInfos = getCustomerIdInfo(customerNo);
            map.put("idInfos", idInfos);
            //客户角色信息
            List<Map<String, Object>> customerRoles = getCustomerRoles(customerNo);
            map.put("customerRoles", customerRoles);
            //客户联系信息
            List<Map<String, Object>> contacts = getCustomerContacts(customerNo);
            map.put("contacts", contacts);
            //客户转化来源
            List<Map<String, Object>> preChanges = getCustomerChange(customerNo);
            map.put("preChanges", preChanges);
            return map;
        } catch (DataAccessException e) {
            log.info("个人客户详情查询异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> selectCompanyExtend(String customerNo) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            //客户角色信息
            List<Map<String, Object>> customerRoles = getCustomerRoles(customerNo);
            map.put("customerRoles", customerRoles);
            //客户联系信息
            List<Map<String, Object>> contacts = getCustomerContacts(customerNo);
            map.put("contacts", contacts);
            //客户转化来源
            List<Map<String, Object>> preChanges = getCustomerChange(customerNo);
            map.put("preChanges", preChanges);
            return map;
        } catch (DataAccessException e) {
            log.info("对公客户详情查询异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    private List<Map<String, Object>> getCustomerIdInfo(String customerNo) {
        try {
            List<Map<String, Object>> idInfos = new ArrayList<>();
            //个人证件信息
            Example example = new Example(CustomerIdInfoPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", customerNo);
            List<CustomerIdInfoPo> idInfoList = customerIdInfoMapper.selectByExample(example);
            CustomerManageInfoPo po = new CustomerManageInfoPo();
            po.setCustomerNo(customerNo);
            List<CustomerManageInfoPo> list = customerManageInfoMapper.select(po);
            desensitizationService.desensitizationList(idInfoList);
            for (CustomerIdInfoPo idInfoPo : idInfoList) {
                Map<String, Object> idInfo = new HashMap<>();
                idInfo.put("customerName", idInfoPo.getCustomerName());
                idInfo.put("idCardType", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(idInfoPo.getIdCardType()));
                idInfo.put("idCardNo", idInfoPo.getIdCardNo());
                List<String> systemList = Arrays.asList(idInfoPo.getSubSystemSign().split(","));
                String subSystemSign = "";
                if (list != null && list.size() > 0) {
                    for (CustomerManageInfoPo data : list) {
                        subSystemSign += cacheService.getSystemNameBySign(data.getSubSystemSign()) + "  ";
                    }
                }
                idInfo.put("subSystemSign", subSystemSign);
                idInfo.put("createTime", idInfoPo.getCreateTime() != null ? DateTimeUtils.dateToStrLong(idInfoPo.getCreateTime()) : "");
                idInfo.put("updateTime", idInfoPo.getUpdateTime() != null ? DateTimeUtils.dateToStrLong(idInfoPo.getUpdateTime()) : "");
                idInfo.put("elementsVerified", idInfoPo.getElementsVerified().equals(CustomerConstants.STATUS_ELEMENTS_VERIFIED) ? "已验证" : "未验证");
                idInfos.add(idInfo);
            }
            return idInfos;
        } catch (DataAccessException e) {
            log.info("查询个人客户证件信息异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    private List<Map<String, Object>> getCustomerRoles(String customerNo) {
        try {
            List<Map<String, Object>> customerRoles = new ArrayList<>();
            Example example = new Example(CustomerRolePo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", customerNo);
            List<CustomerRolePo> customerRolePos = customerRoleMapper.selectByExample(example);
            Map<String, Object> customerRole;
            for (CustomerRolePo po : customerRolePos) {
                customerRole = new HashMap<>();
                customerRole.put("customerRole", DictionaryFactory.Dict.ROLE.getDictMap().get(po.getCustomerRole()));
                customerRole.put("systemSign", cacheService.getSystemNameBySign(po.getSystemSign()));
                customerRole.put("subSystemSign", cacheService.getSystemNameBySign(po.getSubSystemSign()));
                customerRole.put("status", po.getRoleStatus().equals(CustomerConstants.CUSTOMER_ROLE_EFFECTIVE) ? "使用中" : "已停止");
                customerRole.put("createTime", CustomerUtils.timestamp2Stirng(po.getCreateTime()));
                customerRole.put("updateTime", CustomerUtils.timestamp2Stirng(po.getUpdateTime()));
                customerRoles.add(customerRole);
            }
            return customerRoles;
        } catch (DataAccessException e) {
            log.info("查询客户角色报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    private List<Map<String, Object>> getCustomerContacts(String customerNo) {
        try {
            List<Map<String, Object>> contacts = new ArrayList<>();
            //客户联系信息
            Example example1 = new Example(CustomerContactInfoPo.class);
            example1.setDistinct(false);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("customerNo", customerNo);
            List<CustomerContactInfoPo> pos = contactMapper.selectByExample(example1);
            desensitizationService.desensitizationList(pos);
            for (CustomerContactInfoPo contactPo : pos) {
                Map<String, Object> contact = new HashMap<>();
                contact.put("contactType", DictionaryFactory.Dict.CONTACT_TYPE.getDictMap().get(contactPo.getContactType()));
                contact.put("contactInfo", contactPo.getContactInfo());
                contact.put("createTime", contactPo.getCreateTime() != null ? DateTimeUtils.dateToStrLong(contactPo.getCreateTime()) : "");
                contact.put("updateTime", contactPo.getUpdateTime() != null ? DateTimeUtils.dateToStrLong(contactPo.getUpdateTime()) : "");
                contact.put("systemSign", cacheService.getSystemNameBySign(contactPo.getSystemSign()));
                contact.put("subSystemSign", cacheService.getSystemNameBySign(contactPo.getSubSystemSign()));
                contacts.add(contact);
            }
            return contacts;
        } catch (DataAccessException e) {
            log.info("查询客户联系信息异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    private List<Map<String, Object>> getCustomerChange(String customerNo) {
        try {
            //todo 做客户号合并时新增来源类型字段记录客户号来源
            List<Map<String, Object>> preChanges = new ArrayList<>();
            Example example = new Example(CustomerExtendPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", customerNo);
            List<CustomerExtendPo> pos = customerExtendMapper.selectByExample(example);
            for (CustomerExtendPo po : pos) {
                Map<String, Object> preChange = new HashMap<>();
                preChange.put("preCustomerNo", po.getPreCustomerNo());
                preChange.put("preType", DictionaryFactory.Dict.CUSTOMER_SOURCE_TYPE.getDictMap().get("1"));
                preChange.put("updateTime", po.getUpdateTime() != null ? DateTimeUtils.dateToStrLong(po.getUpdateTime()) : "");
                preChange.put("subSystemSign", cacheService.getSystemNameBySign(po.getSubSystemSign()));
                preChanges.add(preChange);
            }
            Example example1 = new Example(CustomerMergeFlowPo.class);
            example1.setDistinct(false);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("mergeCustomerNo", customerNo);
            List<CustomerMergeFlowPo> pos1 = customerMergeFlowMapper.selectByExample(example1);
            for (CustomerMergeFlowPo po : pos1) {
                Map<String, Object> preChange = new HashMap<>();
                preChange.put("preCustomerNo", po.getCustomerNo());
                preChange.put("preType", DictionaryFactory.Dict.CUSTOMER_SOURCE_TYPE.getDictMap().get("2"));
                preChange.put("updateTime", po.getCreateTime() != null ? DateTimeUtils.dateToStrLong(po.getCreateTime()) : "");
                List<String> systemList = Arrays.asList(po.getSubSystemSign().split(","));
                String subSystemSign = "";
                for (String system : systemList) {
                    subSystemSign += cacheService.getSystemNameBySign(system) + "  ";
                }
                preChange.put("subSystemSign", subSystemSign);
                preChanges.add(preChange);
            }
            return preChanges;
        } catch (DataAccessException e) {
            log.info("查询客户转化情况异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    private List<Map<String, Object>> getPreChange(String preCustomerNo) {
        try {
            List<Map<String, Object>> preChanges = new ArrayList<>();
            Example example = new Example(CustomerExtendPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("preCustomerNo", preCustomerNo);
            criteria.andEqualTo("status", 1);
            List<CustomerExtendPo> pos = customerExtendMapper.selectByExample(example);
            if (pos.size() > 0) {
                for (CustomerExtendPo po : pos) {
                    Map<String, Object> preChange = new HashMap<>();
                    preChange.put("customerNo", po.getCustomerNo());
                    preChange.put("createTime", po.getCreateTime() != null ? DateTimeUtils.dateToStrLong(po.getCreateTime()) : "");
                    preChange.put("updateTime", po.getUpdateTime() != null ? DateTimeUtils.dateToStrLong(po.getUpdateTime()) : "");
                    preChange.put("systemSign", cacheService.getSystemNameBySign(po.getSystemSign()));
                    preChange.put("subSystemSign", cacheService.getSystemNameBySign(po.getSubSystemSign()));
                    preChanges.add(preChange);
                }
            }
            return preChanges;
        } catch (DataAccessException e) {
            log.error("查询客户转化情况异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> updateCompany(String id, String legalName, String idCardType, String idCardNo) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            CustomerUtils.checkIdCardTypeAndNo(idCardType, idCardNo);
            Example example = new Example(CompanyIdInfoPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("legalName", legalName);
            criteria.andEqualTo("idCardType", idCardType);
            criteria.andEqualTo("idCardNo", idCardNo);
            List<CompanyIdInfoPo> poList = companyIdInfoMapper.selectByExample(example);
            if (poList != null && poList.size() > 0) {
                String customerNo = poList.get(0).getCustomerNo();
                map.put("status", 1);
                map.put("content", customerNo);
            } else {
                CompanyIdInfoPo po = companyIdInfoMapper.selectByPrimaryKey(id);
                String subSystemSign = po.getSubSystemSign();
                map.put("status", 0);
                map.put("content", subSystemSign);
            }
            return map;
        } catch (DataAccessException e) {
            log.info("法人证件信息修改异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> updateCompanyNotice(String id, String customerNo, String legalName, String idCardType, String idCardNo) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            int status = 1;
            CompanyIdInfoPo po = new CompanyIdInfoPo();
            CompanyIdInfoPo oldPo = companyIdInfoMapper.selectByPrimaryKey(id);
            po.setId(id);
            po.setLegalName(legalName);
            po.setIdCardType(idCardType);
            po.setIdCardNo(idCardNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            //更新证件信息表
            int res = companyIdInfoMapper.updateByPrimaryKeySelective(po);
            if (res > 0) {
                status = 0;
                String oldCustomerName = oldPo.getLegalName();
                String oldIdCardType = oldPo.getIdCardType();
                String oldIdCardNo = oldPo.getIdCardNo();
                String subSystemSign = oldPo.getSubSystemSign();
                List<String> receiverList = Arrays.asList(StringUtils.split(subSystemSign, ","));
                for (String receiver : receiverList) {
                    commonService.sendHttpMsg(receiver, id, customerNo, legalName, idCardType, idCardNo, oldCustomerName, oldIdCardType, oldIdCardNo);
                }
            }
            map.put("status", status);
            return map;
        } catch (DataAccessException e) {
            log.info("法人证件信息修改异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }


    @Override
    public Map<String, Object> updatePerson(String id, String customerName, String idCardType, String idCardNo) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            CustomerUtils.checkIdCardTypeAndNo(idCardType, idCardNo);
            Example example = new Example(CustomerIdInfoPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerName", customerName);
            criteria.andEqualTo("idCardType", idCardType);
            criteria.andEqualTo("idCardNo", idCardNo);
            List<CustomerIdInfoPo> poList = customerIdInfoMapper.selectByExample(example);
            if (poList != null && poList.size() > 0) {
                String customerNo = poList.get(0).getCustomerNo();
                map.put("status", 1);
                map.put("content", customerNo);
            } else {
                CustomerIdInfoPo po = customerIdInfoMapper.selectByPrimaryKey(id);
                String subSystemSign = po.getSubSystemSign();
                map.put("status", 0);
                map.put("content", subSystemSign);
            }
            return map;
        } catch (DataAccessException e) {
            log.info("个人证件信息修改异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> updatePersonNotice(String id, String customerNo, String customerName, String idCardType, String idCardNo) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            int status = 1;
            CustomerIdInfoPo oldPo = customerIdInfoMapper.selectByPrimaryKey(id);
            CustomerIdInfoPo po = new CustomerIdInfoPo();
            po.setId(id);
            po.setCustomerName(customerName);
            po.setIdCardType(idCardType);
            po.setIdCardNo(idCardNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            //更新证件信息表
            int res = customerIdInfoMapper.updateByPrimaryKeySelective(po);
            if (res > 0) {
                status = 0;
                //todo 通知相关业务系统
                String oldCustomerName = oldPo.getCustomerName();
                String oldIdCardType = oldPo.getIdCardType();
                String oldIdCardNo = oldPo.getIdCardNo();
                String subSystemSign = oldPo.getSubSystemSign();
                List<String> receiverList = Arrays.asList(StringUtils.split(subSystemSign, ","));
                for (String receiver : receiverList) {
                    commonService.sendHttpMsg(receiver, id, customerNo, customerName, idCardType, idCardNo, oldCustomerName, oldIdCardType, oldIdCardNo);
                }
            }
            map.put("status", status);
            return map;
        } catch (DataAccessException e) {
            log.info("个人证件信息修改异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> editMergePerson(String id, String customerNo, String mergeId, String mergeCustomerNo) {
        try {
            log.info("信息合并处理开始,合并后客户号：" + customerNo + ", 被合并客户号：" + mergeCustomerNo);
            CustomerIdInfoPo newPo = customerIdInfoMapper.selectByPrimaryKey(id);
            CustomerIdInfoPo oldPo = customerIdInfoMapper.selectByPrimaryKey(mergeId);
            Map<String, Object> map = new HashMap<>(2);
            Example example = new Example(CustomerIdInfoPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", customerNo);
            List<CustomerIdInfoPo> poList = customerIdInfoMapper.selectByExample(example);
            Example example1 = new Example(CustomerIdInfoPo.class);
            example1.setDistinct(false);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("customerNo", mergeCustomerNo);
            List<CustomerIdInfoPo> mergeList = customerIdInfoMapper.selectByExample(example1);
            Integer status = ((CustomerInfoServiceImpl) AopContext.currentProxy()).merge(customerNo, mergeCustomerNo, mergeList, poList);
//            //正常情况合并，一对一合并
//            if (mergeList.size() == 1 && poList.size() == 1) {
//                status = ((CustomerInfoServiceImpl) AopContext.currentProxy()).merge(mergeId, mergeCustomerNo, customerNo, mergeList, poList, 1);
//            }
//            //被合并客户号多个证件信息，合并客户号只有一个
//            if (mergeList.size() > 1 && poList.size() == 1) {
//                status = ((CustomerInfoServiceImpl) AopContext.currentProxy()).merge(mergeId, mergeCustomerNo, customerNo, mergeList, poList, 2);
//            }
//            //被合并客户号只存在一个证件，合并后客户号存在多个证件，被合并客户号证件类型已存在则不可以合并,不存在则可以合并,同一个三要素不可能由不同客户号使用，开户不会成功，规避此类判断
//            if (mergeList.size() == 1 && poList.size() > 1) {
//                status = ((CustomerInfoServiceImpl) AopContext.currentProxy()).merge(mergeId, mergeCustomerNo, customerNo, mergeList, poList, 3);
//            }
//            //被合并与合并客户号均存在多个证件
//            if (mergeList.size() > 1 && poList.size() > 1) {
//                status = ((CustomerInfoServiceImpl) AopContext.currentProxy()).merge(mergeId, mergeCustomerNo, customerNo, mergeList, poList, 4);
//            }
            if (status == 0) {
                String idCardType = newPo.getIdCardType();
                String idCardNo = newPo.getIdCardNo();
                String customerName = newPo.getCustomerName();
                String subSystemSign = oldPo.getSubSystemSign();
                List<String> receiverList = Arrays.asList(StringUtils.split(subSystemSign, ","));
                for (String receiver : receiverList) {
                    commonService.sendMergeNotice(receiver, id, customerNo, customerName, idCardType, idCardNo, mergeCustomerNo);
                }
            }
            map.put("status", status);
            return map;
        } catch (CustomerException e) {
            log.info("客户合并异常>>>{}", e.getMsg());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    /**
     * 1 删除客户主表客户号
     * 2 更新证件信息表客户号
     * 3 若变更客户号由用户号转化，需要更新
     * 4 更新客户联系信息表
     * 5 更新客户关系信息表
     * 6 记录原变更客户号，转化来源为合并，前台客户详情需要展示此项,在cust_merge_flow保存合并前客户号
     * 7 更新原客户号对应产品购买信息以及账户信息表
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer merge(String customerNo, String mergeCustomerNo, List<CustomerIdInfoPo> mergeList, List<CustomerIdInfoPo> poList) {
//        if (type == 1) {
//            insertCustomerMerge(customerNo, mergeList.get(0));
//            updateCustomerIdInfo(customerNo, mergeId);
//        } else if (type == 2) {
//            for (CustomerIdInfoPo mergePo : mergeList) {
//                insertCustomerMerge(customerNo, mergePo);
//                mergeCustomerIdInfo(mergeId, customerNo, mergePo, poList);
//            }
//        } else if (type == 3) {
//            insertCustomerMerge(customerNo, mergeList.get(0));
//            mergeCustomerIdInfo(mergeId, customerNo, mergeList.get(0), poList);
//        } else if (type == 4) {
//            for (CustomerIdInfoPo mergePo : mergeList) {
//                insertCustomerMerge(customerNo, mergePo);
//                mergeCustomerIdInfo(mergeId, customerNo, mergePo, poList);
//            }
//        }
        for (CustomerIdInfoPo mergePo : mergeList) {
            insertCustomerMerge(customerNo, mergePo);
            mergeCustomerIdInfo(mergePo.getId(), customerNo, mergePo, poList);
        }
        deleteCustomerInfo(mergeCustomerNo);
        //客户联系信息合并,联系信息合并需要去重
        mergeCustomerContact(customerNo, mergeCustomerNo);
        updateCustomerExtend(customerNo, mergeCustomerNo);
        updateRelation(customerNo, mergeCustomerNo);
        updateCustomerProduct(mergeCustomerNo, customerNo);
        updateCustomerAccount(mergeCustomerNo, customerNo);
        updateCustomerRole(mergeCustomerNo, customerNo);
        //todo 同步更新产品及账户信息,客户详情展示添加合并客户号信息,在cust_merge_flow查询历史记录,通知接口需新增合并信息相关信息（后续）
        Integer status = 0;
        return status;
    }

    public void updateCustomerProduct(String oldCustomerNo, String newCustomerNo) {
        try {
            Example example = new Example(CustomerProductInfoPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", oldCustomerNo);
            CustomerProductInfoPo po = new CustomerProductInfoPo();
            po.setCustomerNo(newCustomerNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            customerProductMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.info("更新产品信息cust_product_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    public void updateCustomerAccount(String oldCustomerNo, String newCustomerNo) {
        try {
            Example example = new Example(CustomerAccountPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", oldCustomerNo);
            CustomerAccountPo po = new CustomerAccountPo();
            po.setCustomerNo(newCustomerNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            accountMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.info("更新账户信息cust_account_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    public void updateCustomerRole(String oldCustomerNo, String newCustomerNo) {
        try {
            Example example = new Example(CustomerRolePo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", oldCustomerNo);
            CustomerRolePo po = new CustomerRolePo();
            po.setCustomerNo(newCustomerNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            customerRoleMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.info("更新角色信息cust_role相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    private void mergeCustomerIdInfo(String mergeId, String customerNo, CustomerIdInfoPo mergePo, List<CustomerIdInfoPo> poList) {
        try {
            // 判断合并后系统标识是否包含，不包含择则添加，并且删除原证件信息
            Boolean flag = false;
            for (CustomerIdInfoPo po : poList) {
                if (po.getIdCardType().equals(mergePo.getIdCardType())) {
                    flag = true;
                    String mergeSubSystemSign = mergePo.getSubSystemSign();
                    String subSystemSign = po.getSubSystemSign();
                    String tempSystemSign = subSystemSign + "," + mergeSubSystemSign;
                    String result = mergeSystemSign(tempSystemSign);
                    po.setSubSystemSign(result);
                    po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                    customerIdInfoMapper.updateByPrimaryKeySelective(po);
                }
            }
            if (flag) {
                //todo 发送通知信息
                deleteCustomerIdInfo(mergeId);
            } else {
                insertCustomerIdInfo(customerNo, mergePo);
                deleteCustomerIdInfo(mergeId);
            }

        } catch (DataAccessException e) {
            log.info("合并客户的时候更新cust_id_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    private String mergeSystemSign(String systemSign) {
        Set<String> set = new TreeSet<String>();
        for (String s : systemSign.split(",")) {
            set.add(s);
        }
        String result = StringUtils.strip(Arrays.toString(set.toArray()).replace(" ", ""), "[]");
        log.info("合并客户号为:" + result);
        return result;
    }

    private void insertCustomerMerge(String customerNo, CustomerIdInfoPo idInfoPo) {
        try {
            CustomerMergeFlowPo po = new CustomerMergeFlowPo();
            po.setId(UUIDUtils.getUUID());
            po.setMergeCustomerNo(customerNo);
            po.setMergeId(idInfoPo.getId());
            po.setCustomerName(idInfoPo.getCustomerName());
            po.setCustomerNo(idInfoPo.getCustomerNo());
            po.setIdCardNo(idInfoPo.getIdCardNo());
            po.setIdCardType(idInfoPo.getIdCardType());
            po.setSubSystemSign(idInfoPo.getSubSystemSign());
            po.setCreateTime(new Timestamp(System.currentTimeMillis()));
            customerMergeFlowMapper.insert(po);
        } catch (DataAccessException e) {
            log.info("合并客户的时候新增cust_merge_flow相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_INSERT);
        }
    }

    private void deleteCustomerInfo(String mergeCustomerNo) {
        try {
            CustomerInfoPo po = new CustomerInfoPo();
            po.setCustomerNo(mergeCustomerNo);
            customerMapper.delete(po);
        } catch (DataAccessException e) {
            log.info("合并客户的时候删除cust_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_DELETE);
        }
    }

    private void insertCustomerIdInfo(String customerNo, CustomerIdInfoPo idInfoPo) {
        try {
            CustomerIdInfoPo po = new CustomerIdInfoPo();
            BeanUtils.copyProperties(idInfoPo, po);
            po.setCustomerNo(customerNo);
            po.setId(UUIDUtils.getUUID());
            po.setCreateTime(new Timestamp(System.currentTimeMillis()));
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            customerIdInfoMapper.insert(po);
        } catch (DataAccessException e) {
            log.info("合并客户的时候新增cust_id_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_INSERT);
        }
    }

    private void deleteCustomerIdInfo(String mergeId) {
        try {
            customerIdInfoMapper.deleteByPrimaryKey(mergeId);
        } catch (DataAccessException e) {
            log.info("合并客户的时候删除cust_id_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_INSERT);
        }
    }

    private void mergeCustomerContact(String customerNo, String mergeCustomerNo) {
        try {
            CustomerContactInfoPo po1 = new CustomerContactInfoPo();
            po1.setCustomerNo(customerNo);
            List<CustomerContactInfoPo> list1 = contactMapper.select(po1);
            CustomerContactInfoPo po2 = new CustomerContactInfoPo();
            po2.setCustomerNo(mergeCustomerNo);
            List<CustomerContactInfoPo> list2 = contactMapper.select(po2);
            if (list2 != null && list2.size() > 0) {
                for (CustomerContactInfoPo contactInfoPo2 : list2) {
                    Boolean flag = false;
                    if (list1 != null && list1.size() > 0) {
                        for (CustomerContactInfoPo contactInfoPo1 : list1) {
                            if (contactInfoPo1.getContactType().equals(contactInfoPo2.getContactType()) && contactInfoPo1.getContactInfo().equals(contactInfoPo2.getContactInfo()) && contactInfoPo1.getSubSystemSign().equals(contactInfoPo2.getSubSystemSign())) {
                                flag = true;
                            }
                        }
                    }
                    if (flag) {
                        deleteCustomerContact(contactInfoPo2.getId());
                    } else {
                        updateCustomerContact(customerNo, contactInfoPo2.getId());
                    }
                }
            }
        } catch (DataAccessException e) {
            log.info("合并客户的时候更新cust_contact_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    private void updateCustomerContact(String customerNo, String mergeId) {
        try {
            CustomerContactInfoPo po = new CustomerContactInfoPo();
            po.setCustomerNo(customerNo);
            po.setId(mergeId);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            contactMapper.updateByPrimaryKeySelective(po);
        } catch (DataAccessException e) {
            log.info("合并客户的时候更新cust_contact_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    private void deleteCustomerContact(String id) {
        try {
            customerMapper.selectByPrimaryKey(id);
        } catch (DataAccessException e) {
            log.info("合并客户的时候删除cust_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_DELETE);
        }
    }

    private void updateCustomerExtend(String customerNo, String mergeCustomerNo) {
        try {
            Example example = new Example(CustomerExtendPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", mergeCustomerNo);
            CustomerExtendPo po = new CustomerExtendPo();
            po.setCustomerNo(customerNo);
            customerExtendMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.info("合并客户的时候更新cust_extend相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    public void updateRelation(String customerNo, String mergeCustomerNo) {
        try {
            Example example = new Example(CustomerRelationInfoPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", mergeCustomerNo);
            CustomerRelationInfoPo po = new CustomerRelationInfoPo();
            po.setCustomerNo(customerNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            relationMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.info("合并客户的时候更新cust_relation_info相关信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> editMergeBizInfo(String id, String customerNo, String mergeId, String mergeCustomerNo, String bizId) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            CustomerIdInfoPo oldPo = customerIdInfoMapper.selectByPrimaryKey(mergeId);
            CustomerIdInfoPo newPo = customerIdInfoMapper.selectByPrimaryKey(id);
            Example example = new Example(CustomerIdInfoPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", customerNo);
            List<CustomerIdInfoPo> poList = customerIdInfoMapper.selectByExample(example);
            Example example1 = new Example(CustomerIdInfoPo.class);
            example1.setDistinct(false);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("customerNo", mergeCustomerNo);
            List<CustomerIdInfoPo> mergeList = customerIdInfoMapper.selectByExample(example1);
            Integer status = ((CustomerInfoServiceImpl) AopContext.currentProxy()).merge(customerNo, mergeCustomerNo, mergeList, poList);
            //todo 定时任务，查询未处理异常信息，发邮件给相应系统
            //todo 定时任务获取我方已修改信息，但业务端还未修改异常信息
            if (status == 0) {
                //todo 通知相关业务系统
                String idCardType = newPo.getIdCardType();
                String idCardNo = newPo.getIdCardNo();
                String customerName = newPo.getCustomerName();
                String subSystemSign = oldPo.getSubSystemSign();
                List<String> receiverList = Arrays.asList(StringUtils.split(subSystemSign, ","));
                int succCount = 0;
                for (String receiver : receiverList) {
                    String noticeRes = commonService.sendMergeNotice(receiver, id, customerNo, customerName, idCardType, idCardNo, mergeCustomerNo);
                    if (noticeRes != null && "0".equals(noticeRes)) {
                        succCount++;
                    }
                    //若成功，更新业务订单表状态为已合并处理
                    BizModifyPo bizPo = new BizModifyPo();
                    bizPo.setId(bizId);
                    bizPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                    bizPo.setStatus(CustomerConstants.BIZ_MODIFY_STATUS_MERGE);
                    if (succCount == receiverList.size()) {
                        bizPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_SUCCESS);
                    } else {
                        bizPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_FAIL);
                    }
                    bizMapper.updateByPrimaryKeySelective(bizPo);
                    //合并完成后邮件通知
//                String emailContent = "您好,客户号：" + mergeCustomerNo + "已合并至新的客户号 " + customerNo + " ,请知悉，并做相应修改";
//                EmailSendRo ro = new EmailSendRo();
//                ro.setSubject("异常信息合并处理通知[一账通]");
//                ro.setBody(emailContent);
//                commonService.sendEmail(ro);
                }
            }
            map.put("status", status);
            return map;
        } catch (CustomerException e) {
            log.info("客户合并异常>>>{}", e.getMsg());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> editMergeBizInfo(String id) {
        try {
            Map<String, Object> map = new HashMap<>(1);
            Map<String, Object> oldInfo = new HashMap<>(1);
            BizModifyPo bizPo = bizMapper.selectByPrimaryKey(id);
            CustomerIdInfoPo newIdInfoPo = commonService.getExistCustomerInfo(bizPo.getCustomerName(), bizPo.getIdCardType(), bizPo.getIdCardNo());
            if (newIdInfoPo == null) {
                bizPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                bizPo.setRemark("变更证件信息未被其他客户号使用，请使用变更处理");
                bizMapper.updateByPrimaryKeySelective(bizPo);
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "变更证件信息未被其他客户号使用，请使用变更处理");
            }
            List<CustomerIdInfoPo> idInfoPos = commonService.getAllCustomer(bizPo.getCustomerNo(), bizPo.getSystemSign(), bizPo.getSubSystemSign());
            if (oldInfo == null || idInfoPos.size() < 1) {
                bizPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                bizPo.setRemark("原证件类型不存在");
                bizMapper.updateByPrimaryKeySelective(bizPo);
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "证件信息合并失败，原证件类型不存在");
            }
            for (CustomerIdInfoPo idInfoPo : idInfoPos) {
                if (idInfoPo.getIdCardType().equals(bizPo.getIdCardType())) {
                    oldInfo.put("customerName", idInfoPo.getCustomerName());
                    oldInfo.put("idCardTypeName", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(idInfoPo.getIdCardType()));
                    oldInfo.put("idCardType", idInfoPo.getIdCardType());
                    oldInfo.put("idCardNo", idInfoPo.getIdCardNo());
                    oldInfo.put("id", idInfoPo.getId());
                    oldInfo.put("customerNo", idInfoPo.getCustomerNo());
                }
            }
            Map<String, Object> newInfo = new HashMap<>(1);
            newInfo.put("customerName", newIdInfoPo.getCustomerName());
            newInfo.put("idCardTypeName", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(newIdInfoPo.getIdCardType()));
            newInfo.put("idCardType", newIdInfoPo.getIdCardType());
            newInfo.put("idCardNo", newIdInfoPo.getIdCardNo());
            newInfo.put("id", newIdInfoPo.getId());
            newInfo.put("customerNo", newIdInfoPo.getCustomerNo());
            map.put("newInfo", newInfo);
            map.put("oldInfo", oldInfo);
            return map;
        } catch (DataAccessException e) {
            log.info("证件信息合并报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> editBizNotice(String id, String customerNo, String customerName, String idCardType, String idCardNo, Integer type) {
        try {
            Map<String, Object> map = new HashMap<>(2);
            String subSystemSign = "";
            Integer status = 1;
            //1 证件信息变更处通知(单条)  2业务系统变更处通知
            if (type == 1) {
                CustomerContactFlowPo contactFlowPo = contactFlowMapper.selectByPrimaryKey(id);
                subSystemSign = contactFlowPo.getSubSystemSign();
            } else if (type == 2) {
                CustomerIdInfoPo idInfoPo = commonService.getExistCustomerInfo(customerName, idCardType, idCardNo);
                subSystemSign = idInfoPo.getSubSystemSign();
            }
            List<String> receiverList = Arrays.asList(StringUtils.split(subSystemSign, ","));
            int succCount = 0;
            for (String receiver : receiverList) {
                String noticeRes = commonService.sendMergeNotice(receiver, id, customerNo, customerName, idCardType, idCardNo, null);
                if (noticeRes != null && "0".equals(noticeRes)) {
                    succCount++;
                }
            }
            //若成功，更新业务订单表状态为已合并处理
            if (type == 2) {
                BizModifyPo bizPo = new BizModifyPo();
                bizPo.setId(id);
                bizPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                bizPo.setStatus(CustomerConstants.BIZ_MODIFY_STATUS_MERGE);
                if (succCount == receiverList.size()) {
                    bizPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_SUCCESS);
                    status = 0;
                } else {
                    bizPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_FAIL);
                }
                bizMapper.updateByPrimaryKeySelective(bizPo);
            } else if (type == 1) {
                CustomerContactFlowPo modifyPo = new CustomerContactFlowPo();
                modifyPo.setId(id);
                if (succCount == receiverList.size()) {
                    modifyPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_SUCCESS);
                    status = 0;
                } else {
                    modifyPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_FAIL);
                }
                contactFlowMapper.updateByPrimaryKeySelective(modifyPo);
            }
            map.put("status", status);
            return map;
        } catch (CustomerException e) {
            log.info("发送通知信息报错>>>{}", e.getMsg());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public PageInfo<PreCustomerInfoVo> selectAllPreV2(PreCustomerInfoRo ro) {
        boolean queryByOldMethod = StringUtils.isNotBlank(ro.getPreCustomerNo()) || StringUtils.isNotBlank(ro.getContactInfo());
        if (queryByOldMethod) {
            return this.selectAllPre(ro);
        }
        return this.selectAllPreBySubSystemSigns(ro);
    }

    private PageInfo<PreCustomerInfoVo> selectAllPreBySubSystemSigns(PreCustomerInfoRo ro) {
        List<PreCustomerInfoPo> infoPos = new ArrayList<>();
        Integer total = 0;

        // 没选系统来源
        int systemSignNumber = ro.getSubSystemSigns().size();
        if (0 == systemSignNumber) {
            computePage(ro);
            infoPos = customerManagerMapper.getListByNoSystemSign(ro);
            ro.getSubSystemSigns().add("ALL");
            total = this.getCountByOneSubSystemSign(ro);
            ro.getSubSystemSigns().clear();
        }

        // 选择1个系统来源
        if (1 == systemSignNumber) {
            computePage(ro);
            infoPos = customerManagerMapper.getListByOneSubSystemSign(ro, ro.getSubSystemSigns().get(0));
            total = this.getCountByOneSubSystemSign(ro);
        }

        // 选择多个系统来源
        if (1 < systemSignNumber) {
            Page<PreCustomerInfoPo> page = PageHelper.startPage(ro.getPageNo(), ro.getPageSize());
            infoPos = customerManagerMapper.getListByMultiSubSystemSign(ro, ro.getSubSystemSigns().size());
            total = (int) page.getTotal();
        }

        desensitizationService.desensitizationList(infoPos);
        List<PreCustomerInfoVo> vos = infoPos.parallelStream().map(po -> convert(po)).collect(Collectors.toList());
        return new PageInfo<>(vos, total, ro.getPageNo(), ro.getPageSize());
    }

    private void computePage(PreCustomerInfoRo ro) {
        Integer pageNo = ro.getPageNo();
        Integer pageSize = ro.getPageSize();
        if (Objects.isNull(pageNo) || pageNo < 0 || Integer.MAX_VALUE < pageNo) {
            pageNo = 1;
        }
        if (Objects.isNull(pageSize) || pageSize < 0 || Integer.MAX_VALUE < pageSize) {
            pageSize = 10;
        }
        Integer startPage = (pageNo - 1) * pageSize;
        ro.setPageSize(pageSize);
        ro.setPageNo(pageNo);
        ro.setStartPage(startPage);
    }

    private Integer getCountByOneSubSystemSign(PreCustomerInfoRo ro) {
        String subSystemSign = ro.getSubSystemSigns().get(0);
        CustomerExtendStatisticPo po = new CustomerExtendStatisticPo();
        po.setSubSystemSign(subSystemSign);

        Integer total = 0;
        Integer startDateNum = 0;
        Integer endDateNum = 0;
        Integer currentDayNum = 0;

        // 校验创建日期参数
        LocalDate currentDate = LocalDate.now();
        DateParam dateParam = new DateParam().validateDate(currentDate, ro.getCreateTimeStart(), ro.getCreateTimeEnd());
        if (!dateParam.valid) {
            return total;
        }
        LocalDate startDate = dateParam.getStartDate();
        LocalDate endDate = dateParam.getEndDate();
        boolean beCurrentDay = ObjectUtils.equals(endDate, currentDate);

        // 查询结束日期前一天的记录(数据库表中统计的sum包括当天的数据)
        po.setDate(endDate.minusDays(1));
        List<CustomerExtendStatisticPo> endPolist = customerExtendStatisticMapper.select(po);
        if (CollectionUtils.isNotEmpty(endPolist)) {
            endDateNum = endPolist.get(0).getSum();
        }

        // 如果结束日期是当天, 则需要查当天的记录
        if (beCurrentDay) {
            if (StringUtils.equalsIgnoreCase(subSystemSign, "ALL")) {
                currentDayNum = this.queryCurrentDayFroPre(subSystemSign);
            } else {
                currentDayNum = this.queryCurrentDayFromsCust(subSystemSign);
            }
        }

        // 查询开始日期前一天的记录(数据库表中统计的sum包括当天的数据)
        List<CustomerExtendStatisticPo> startPoList = new ArrayList<>();
        if (Objects.nonNull(startDate)) {
            po.setDate(startDate.minusDays(1));
            startPoList = customerExtendStatisticMapper.select(po);
        }
        if (CollectionUtils.isNotEmpty(startPoList)) {
            startDateNum = startPoList.get(0).getSum();
        }

        total = endDateNum + currentDayNum - startDateNum;
        return total;
    }

    private Integer queryCurrentDayFromsCust(String subSystemSign) {
        Timestamp endTime = new Timestamp(System.currentTimeMillis());
        long startTimeMillis = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli();
        Timestamp startTime = new Timestamp(startTimeMillis);
        return customerManagerMapper.queryCurrentDayFromsCust(subSystemSign, startTime, endTime);
    }

    private Integer queryCurrentDayFroPre(String subSystemSign) {
        Timestamp endTime = new Timestamp(System.currentTimeMillis());
        long startTimeMillis = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli();
        Timestamp startTime = new Timestamp(startTimeMillis);
        return customerManagerMapper.queryCurrentDayFromPre(subSystemSign, startTime, endTime);
    }

    private PreCustomerInfoVo convert(PreCustomerInfoPo po) {
        PreCustomerInfoVo vo = new PreCustomerInfoVo();
        BeanUtils.copyProperties(po, vo);
        if (po.getCreateTime() != null) {
            vo.setCreateTime(DateTimeUtils.dateToStrLong(po.getCreateTime()));
        }
        if (po.getUpdateTime() != null) {
            vo.setUpdateTime(DateTimeUtils.dateToStrLong(po.getUpdateTime()));
        }
        //发送方式
        Map<String, String> contactTypeMap = DictionaryFactory.Dict.CONTACT_TYPE.getDictMap();
        if (StringUtils.isNotEmpty(po.getContactType())) {
            vo.setContactType(contactTypeMap.get(po.getContactType()));
        }
        return vo;
    }

    @Data
    private class DateParam {

        private LocalDate startDate;
        private LocalDate endDate;
        private Boolean valid = Boolean.FALSE;

        private DateParam validateDate(LocalDate currentDate, String createTimeStart, String createTimeEnd) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            if (StringUtils.isNotBlank(createTimeStart)) {
                startDate = LocalDate.parse(createTimeStart, formatter);
            }
            if (StringUtils.isNotBlank(createTimeEnd)) {
                endDate = LocalDate.parse(createTimeEnd, formatter);
            } else {
                endDate = currentDate;
            }
            if (Objects.nonNull(startDate) && startDate.isAfter(endDate)) {
                return this;
            }
            if (Objects.nonNull(startDate) && startDate.isAfter(currentDate)) {
                return this;
            }
            if (endDate.isAfter(currentDate)) {
                endDate = currentDate;
            }
            valid = true;
            return this;
        }
    }

}
